/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.scriptmark.core.dispose;

import com.jspx.scriptmark.Phrase;
import com.jspx.scriptmark.core.TagNode;
import com.jspx.scriptmark.core.EnvRunner;
import com.jspx.scriptmark.core.block.IncludeBlock;
import com.jspx.scriptmark.exception.ScriptRunException;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.StringUtil;
import com.jspx.utils.XMLUtil;

import java.io.Writer;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2009-1-2
 * Time: 16:21:03
 */
public class IncludePhrase implements Phrase {
    public IncludePhrase()
    {

    }

    public int getRun(EnvRunner env, TagNode tagNode, Writer out) throws Exception  {
        IncludeBlock includeBlock = (IncludeBlock) tagNode;
        includeBlock.setCurrentPath(env.getCurrentPath());
        includeBlock.setRootDirectory(env.getRootDirectory());
        final String[] jumpName =  new String[]{IncludeBlock.name,IncludeBlock.caption,IncludeBlock.caption,IncludeBlock.encoding,IncludeBlock.file};
        String[] attributeName = includeBlock.getAttributeName();
        if (!ArrayUtil.isEmpty(attributeName))
        for (String varName:attributeName)
        {

            if (StringUtil.isNULL(varName)||ArrayUtil.inArray(jumpName,varName,true)) continue;
            String value = XMLUtil.deleteQuote(includeBlock.getAttribute(varName));
            if (!StringUtil.hasLength(value)) continue;
            try {
                env.getScriptRunner().eval(varName + "=(" + value + ");",includeBlock.getLineNumber());
            } catch (Exception e) {
              throw   new ScriptRunException(includeBlock,"include error expression ,表达式错误:" + value);
            }
        }

        List<TagNode> list = includeBlock.getIncludeNodeList();
        int bc = 0;
        for (TagNode node : list) {
            try{
                bc = env.runBlock(node, out);
            } catch (Exception e) {
                throw new ScriptRunException(node,tagNode.getTagName());
            }
            if (bc != 0) return bc;
        }
        return bc;
    }
}